<script setup lang="ts">
import { useColumnsNow } from "./columnsNow";
import { useColumnsHistory } from "./columnsHistory";
import { Plus } from "@element-plus/icons-vue";
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import CertificateInfoForm from "./CertificateInfoForm.vue";
import { getCertificateList, getCertificateDetail } from "@/api/certificate";
import { getExhibitorId } from "@/utils/getExhibitorId";

defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "certificateInfo"
});

const searchDataNow = ref(""); // 本届证件搜索
const searchDataHistory = ref(""); // 历史证件搜索
const activeName = ref("first"); // 选项卡

// 证件数据
const certificateListNow = ref([]); // 本届证件数据
const certificateListHistory = ref([]); // 历史证件数据
const loadingNow = ref(false);
const loadingHistory = ref(false);

// 分页信息
const paginationNow = ref({
  total: 0,
  page: 1,
  limit: 10
});

const paginationHistory = ref({
  total: 0,
  page: 1,
  limit: 10
});

const handleAdd = () => {
  // 处理新增逻辑，使用 @components已封装好的组件
  console.log("新增数据");
  formMode.value = "add";
  currentFormData.value = null;
  isShowEditDialog.value = true;
};

const formMode = ref<"add" | "view" | "edit">("add");
const currentFormData = ref(null);

const handleView = async (row: any) => {
  // 处理查看逻辑
  console.log("查看数据", row);
  try {
    const result: any = await getCertificateDetail(row.id, row.exhibitor_id);
    if (result.code === 1) {
      formMode.value = "view";
      currentFormData.value = result.data;
      isShowEditDialog.value = true;
    } else {
      ElMessage.error(result.msg || "获取证件详情失败");
    }
  } catch (error) {
    console.error("获取证件详情失败:", error);
    ElMessage.error("获取证件详情失败");
  }
};

const handleEdit = async (row: any) => {
  // 处理修改逻辑
  console.log("修改数据", row);

  // 检查状态，如果状态为0（待审核）或1（已通过），则不允许修改
  if (row.status === 0 || row.status === 1) {
    ElMessage.warning("当前状态不允许修改");
    return;
  }

  try {
    const result: any = await getCertificateDetail(row.id, row.exhibitor_id);
    if (result.code === 1) {
      formMode.value = "edit";
      currentFormData.value = result.data;
      isShowEditDialog.value = true;
    } else {
      ElMessage.error(result.msg || "获取证件详情失败");
    }
  } catch (error) {
    console.error("获取证件详情失败:", error);
    ElMessage.error("获取证件详情失败");
  }
};
// 获取本届证件列表
const getCertificateListNow = async (page = 1, limit = 10) => {
  try {
    loadingNow.value = true;
    // 根据搜索内容判断使用哪个字段
    let username = "";
    let telephone = "";

    if (searchDataNow.value.trim()) {
      // 判断输入的是手机号还是姓名
      const searchValue = searchDataNow.value.trim();
      console.log("本届证件搜索值:", searchValue, "长度:", searchValue.length);

      // 判断是否为手机号：11位数字，以1开头
      if (/^1\d{10}$/.test(searchValue)) {
        // 是手机号
        telephone = searchValue;
        console.log("识别为手机号:", telephone);
      } else {
        // 是姓名
        username = searchValue;
        console.log("识别为姓名:", username);
      }
    }

    console.log("本届证件搜索参数:", {
      searchData: searchDataNow.value,
      username,
      telephone
    });

    const exhibitor_id = getExhibitorId();
    console.log("准备调用API，参数:", {
      page,
      limit,
      exhibitor_id: exhibitor_id,
      certificate_type: "current",
      username: username || undefined,
      telephone: telephone || undefined
    });

    const res: any = await getCertificateList(
      page,
      limit,
      exhibitor_id,
      "current",
      username || undefined,
      telephone || undefined
    );
    console.log("本届证件API调用参数:", {
      page,
      limit,
      exhibitor_id: exhibitor_id,
      certificate_type: "current",
      username: username || undefined,
      telephone: telephone || undefined
    });
    console.log("本届证件API返回的完整数据:", res);
    console.log("本届证件列表数据:", res.data.list);
    certificateListNow.value = res.data.list || [];
    // 更新分页信息
    paginationNow.value = {
      total: res.data.total,
      page: res.data.page,
      limit: res.data.limit
    };
  } catch (error) {
    console.error("获取本届证件列表失败:", error);
    certificateListNow.value = [];
    ElMessage.error("获取本届证件列表失败");
  } finally {
    loadingNow.value = false;
  }
};

// 获取历史证件列表
const getCertificateListHistory = async (page = 1, limit = 10) => {
  try {
    loadingHistory.value = true;
    // 根据搜索内容判断使用哪个字段
    let username = "";
    let telephone = "";

    if (searchDataHistory.value.trim()) {
      // 判断输入的是手机号还是姓名
      const searchValue = searchDataHistory.value.trim();
      console.log("历史证件搜索值:", searchValue, "长度:", searchValue.length);

      // 判断是否为手机号：11位数字，以1开头
      if (/^1\d{10}$/.test(searchValue)) {
        // 是手机号
        telephone = searchValue;
        console.log("识别为手机号:", telephone);
      } else {
        // 是姓名
        username = searchValue;
        console.log("识别为姓名:", username);
      }
    }

    console.log("历史证件搜索参数:", {
      searchData: searchDataHistory.value,
      username,
      telephone
    });

    const exhibitor_id = getExhibitorId();
    const res: any = await getCertificateList(
      page,
      limit,
      exhibitor_id,
      "previous",
      username || undefined,
      telephone || undefined
    );
    console.log("历史证件API调用参数:", {
      page,
      limit,
      exhibitor_id: exhibitor_id,
      certificate_type: "previous",
      username: username || undefined,
      telephone: telephone || undefined
    });
    console.log("历史证件API返回的完整数据:", res);
    console.log("历史证件列表数据:", res.data.list);
    certificateListHistory.value = res.data.list || [];
    // 更新分页信息
    paginationHistory.value = {
      total: res.data.total,
      page: res.data.page,
      limit: res.data.limit
    };
  } catch (error) {
    console.error("获取历史证件列表失败:", error);
    certificateListHistory.value = [];
    ElMessage.error("获取历史证件列表失败");
  } finally {
    loadingHistory.value = false;
  }
};

// 本届证件数据
const { tableDataNow, columnsNow } = useColumnsNow(
  certificateListNow,
  handleView,
  handleEdit,
  () => getCertificateListNow(paginationNow.value.page, 10)
);
// 历史证件数据（传入刷新本届列表的回调）
const { tableDataHistory, columnsHistory } = useColumnsHistory(
  certificateListHistory,
  () => getCertificateListNow(paginationNow.value.page, 10)
);

// 分页改变
const handleCurrentChangeNow = (page: number) => {
  paginationNow.value.page = page;
  getCertificateListNow(page, 10);
};

const handleCurrentChangeHistory = (page: number) => {
  paginationHistory.value.page = page;
  getCertificateListHistory(page, 10);
};

// 本届证件搜索
const handleSearchNow = () => {
  console.log("本届证件搜索触发，搜索内容:", searchDataNow.value);
  paginationNow.value.page = 1; // 重置到第一页
  getCertificateListNow(1, 10);
};

// 历史证件搜索
const handleSearchHistory = () => {
  console.log("历史证件搜索触发，搜索内容:", searchDataHistory.value);
  paginationHistory.value.page = 1; // 重置到第一页
  getCertificateListHistory(1, 10);
};

// 清空本届证件搜索
const handleClearSearchNow = () => {
  searchDataNow.value = "";
  paginationNow.value.page = 1;
  getCertificateListNow(1, 10);
};

// 清空历史证件搜索
const handleClearSearchHistory = () => {
  searchDataHistory.value = "";
  paginationHistory.value.page = 1;
  getCertificateListHistory(1, 10);
};

const handleRefresh = () => {
  // 调用列表查询接口
  console.log("刷新");
  // 根据当前激活的选项卡刷新对应的数据
  if (activeName.value === "first") {
    getCertificateListNow(paginationNow.value.page, 10);
  } else {
    getCertificateListHistory(paginationHistory.value.page, 10);
  }
};

const handleCancel = () => {
  isShowEditDialog.value = false;
  // 清空表单数据
  currentFormData.value = null;
  formMode.value = "add";
};

const handleConfirm = (submitData?: any) => {
  // 处理确认逻辑
  console.log("确认提交", submitData);
  isShowEditDialog.value = false;
  // 清空表单数据
  currentFormData.value = null;
  formMode.value = "add";
  // 刷新本届证件列表
  getCertificateListNow(paginationNow.value.page, 10);
};

const isShowEditDialog = ref(false);

// 组件挂载时获取数据
onMounted(() => {
  getCertificateListNow(1, 10);
  getCertificateListHistory(1, 10);
});
</script>

<template>
  <div class="tab-container">
    <el-tabs v-model="activeName" type="card" style="background-color: white">
      <el-tab-pane label="本地证件" name="first">
        <!-- 本届证件表格 -->
        <!-- 统一的白色背景容器 -->
        <div class="table-container">
          <!-- 自定义头部 -->
          <div class="custom-header">
            <div class="header-left">
              <div class="search-box">
                <el-input
                  v-model="searchDataNow"
                  style="width: 300px; margin-right: 40px"
                  placeholder="手机、姓名"
                  clearable
                  @keyup.enter="handleSearchNow"
                  @clear="handleClearSearchNow"
                />
                <el-button type="primary" @click="handleSearchNow"
                  >搜索</el-button
                >
              </div>
            </div>
            <div class="header-right">
              <el-button type="primary" @click="handleAdd">
                <el-icon><Plus /></el-icon>
                申请证件
              </el-button>
            </div>
          </div>

          <!-- 表格 -->
          <pure-table
            :data="tableDataNow"
            :columns="columnsNow"
            :loading="loadingNow"
            :scroll="{ x: 1800 }"
            style="width: 100%"
            stripe
          />

          <!-- 分页组件 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="paginationNow.page"
              :page-size="10"
              :total="paginationNow.total"
              layout="total, prev, pager, next, jumper"
              @current-change="handleCurrentChangeNow"
            />
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="历史证件" name="second">
        <!-- 历史证件表格 -->
        <!-- 统一的白色背景容器 -->
        <div class="table-container">
          <!-- 自定义头部 -->
          <div class="custom-header">
            <div class="header-left">
              <div class="search-box">
                <el-input
                  v-model="searchDataHistory"
                  style="width: 300px; margin-right: 40px"
                  placeholder="手机、姓名"
                  clearable
                  @keyup.enter="handleSearchHistory"
                  @clear="handleClearSearchHistory"
                />
                <el-button type="primary" @click="handleSearchHistory"
                  >搜索</el-button
                >
              </div>
            </div>
            <div class="header-right">
              <!-- 历史证件不需要新增按钮 -->
            </div>
          </div>

          <!-- 表格 -->
          <pure-table
            :data="tableDataHistory"
            :columns="columnsHistory"
            :loading="loadingHistory"
            :scroll="{ x: 1800 }"
            style="width: 100%"
            stripe
          />

          <!-- 分页组件 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="paginationHistory.page"
              :page-size="10"
              :total="paginationHistory.total"
              layout="total, prev, pager, next, jumper"
              @current-change="handleCurrentChangeHistory"
            />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 弹框放在最外层，避免被其他组件影响 -->

    <el-dialog v-model="isShowEditDialog" :top="'25px'">
      <CertificateInfoForm
        :mode="formMode"
        :initial-data="currentFormData"
        @cancel="handleCancel"
        @confirm="handleConfirm"
      />
    </el-dialog>
  </div>
</template>

<style scoped>
.tab-container {
  padding: 20px;
  background-color: white;
}

/* 统一的白色背景容器 */
.table-container {
  background-color: #fff;
}

/* 自定义头部样式 */
.custom-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
}

.header-left .header-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 分页容器样式 */
.pagination-container {
  padding: 20px 0;
  text-align: center;
  display: flex;
  justify-content: center;
  width: 100%;
}

/* 修改表头背景色 */
:deep(.el-table__header th) {
  background-color: #f2f2f2 !important;
}

/* 修改斑马纹背景色 */
:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #f2f2f2 !important;
}

/* 表格滚动条样式 */
:deep(.el-table) {
  overflow-x: auto;
}

:deep(.el-table__body-wrapper) {
  overflow-x: auto;
}

:deep(.el-table td) {
  padding: 12px 0;
}

/* 固定列样式 */
:deep(.el-table__fixed-right) {
  box-shadow: -2px 0 8px rgb(0 0 0 / 10%);
}

:deep(.el-table__fixed) {
  box-shadow: 2px 0 8px rgb(0 0 0 / 10%);
}

/* 选项卡样式（卡片类型） */
:deep(.el-tabs--card > .el-tabs__header .el-tabs__item) {
  background-color: #ffffff;
  color: #000000;
  border: 1px solid #e5e5e5;
  border-bottom: none;
}

:deep(.el-tabs--card > .el-tabs__header .el-tabs__item.is-active) {
  background-color: #17a1b8;
  color: #ffffff;
  border-color: #17a1b8;
}

:deep(.el-tabs--card > .el-tabs__header .el-tabs__nav) {
  border-bottom: 1px solid #e5e5e5;
}
</style>
